package com.itstyle.seckill.distributedlock.redis;

import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RedissonPerformanceTest2 {
    private static int TOTAL_PRE_THREADS = 400;
    private static long SECONDS = 10;
    protected static boolean isSkipLock = false;
    private static AtomicInteger flag = new AtomicInteger();
    private static AtomicInteger fail = new AtomicInteger();

    public static void main(String[] args) {
        Config config = new Config();
        // for single server
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setPassword("123456");
        final RedissonClient redissonCli = Redisson.create(config);

        RLock lock = null;
        final CountDownLatch startLatch = new CountDownLatch(1);
        final CountDownLatch endLatch = new CountDownLatch(TOTAL_PRE_THREADS);
        //Thread[]  threads = new Thread[TOTAL_PRE_THREADS];
        setZero(redissonCli);

        for (int i = 0; i < TOTAL_PRE_THREADS; i++) {
            PerformanceThread runningThread = new PerformanceThread(startLatch,endLatch,lock,redissonCli);
            runningThread.start();
            //threads[i]=runningThread;
        }

        //开始执行
//        startLatch.countDown();
        try {
            Thread.sleep(SECONDS*1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        for (int i = 0; i < threads.length; i++) {
//            PerformanceThread runningThread =(PerformanceThread)threads[i];
//            runningThread.stopThrad();
//        }

//        try {
//            endLatch.await();
//        } catch (InterruptedException e1) {
//            e1.printStackTrace();
//        }

        printCount(redissonCli);
        redissonCli.shutdown();
    }


    public static class PerformanceThread extends Thread{
        private volatile boolean isRunning = true;
        private CountDownLatch startLatch ;
        private CountDownLatch endLatch;
        private RLock lock;
        private RedissonClient redissonCli;
        private PerformanceThread(CountDownLatch startLatch ,CountDownLatch endLatch,RLock lock ,RedissonClient redissonCli){
            this.startLatch = startLatch;
            this.endLatch = endLatch;
            this.lock = lock;
            this.redissonCli =redissonCli;
        }

        @Override
        public void run() {
//            try {
//                startLatch.await();
//            } catch (InterruptedException e1) {
//                e1.printStackTrace();
//            }
            System.out.println(Thread.currentThread().getName()+"------" + "用户:准备好了------");
            endLatch.countDown();
            try {
                endLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

//            while (isRunning) {
            try {
                System.out.println(Thread.currentThread().getName()+"------" + "lock好了------");
                if (!isSkipLock) {
                    lock = redissonCli.getLock("testLock");
                    boolean a= lock.tryLock(3,10, TimeUnit.SECONDS);
                    if(!a) {
                        fail.getAndIncrement();
                        System.out.println("lock fail");
                    }
                }
                testUpdate(redissonCli);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (!isSkipLock && lock!=null && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            }

        }

        public void stopThrad(){
            isRunning = false;
        }
    }

    /** * 更新对应的记录 */
    public static void testUpdate(RedissonClient redissonCli) {
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        long totalUsed = addLong.addAndGet(1);
        try {
            Thread.sleep(20);
            flag.getAndIncrement();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /** * 最后获得总数 * @param redissonCli */
    public static void printCount(RedissonClient redissonCli){
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        System.out.println("count tps is:"+(addLong.get()/SECONDS));
        System.out.println("count update is:"+flag);
        System.out.println("fail lock is:"+fail);
    }

    /** * 初始化 * @param redissonCli */
    public static void setZero(RedissonClient redissonCli){
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        addLong.set(0);
    }
}
